//
//  PickNumDaLeTouViewController.m
//  PlayBall
//
//  Created by Edward Zhang on 12-5-10.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "JddPickNumDaLeTouViewController.h"
#import "JddViewControllerManager.h"
#import "JddCommonFunction.h"

@interface JddPickNumDaLeTouViewController ()
@end

@implementation JddPickNumDaLeTouViewController

SHARED_VIEW_CONTROLLER_IMPLEMENT(JddPickNumDaLeTouViewController);

@synthesize moneylabel;
@synthesize countlabel;
@synthesize issueCodeLabel;
@synthesize remainTimeLabel;
@synthesize currentLotteryIssue;

- (void)RandomSelectNumViewClickedButtonAtIndex:(NSNumber*)buttonIndex multiple:(NSNumber*)multiple{
    if ([buttonIndex intValue]== 1) {
        
        [lotteryNumberArray removeAllObjects];
        
        for (int i = 0; i < [multiple intValue]; ++i) {
            JddDaletouNumber *number = [[JddDaletouNumber alloc] init];
            [JddCommonFunction generatebackBallOfDaLeTouNumber:number count:2];
            [JddCommonFunction generateheadBallOfDaLeTouNumber:number count:5];
            
            [lotteryNumberArray addObject:number];
        }
        
        [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_PICK_NUM_DALETOU_LIST 
                                                             fromController:self
                                                                 withObject:lotteryNumberArray
                                                                withObject2:nil];
    }
}
-(IBAction)randomSelect:(id)sender{
    
    [lotteryNumberArray removeAllObjects];
    for (int i = 0; i < 5; ++i) {
        JddDaletouNumber *number = [[JddDaletouNumber alloc] init];
        [JddCommonFunction generatebackBallOfDaLeTouNumber:number count:2];
        [JddCommonFunction generateheadBallOfDaLeTouNumber:number count:5];
        [lotteryNumberArray addObject:number];
    }
    [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_PICK_NUM_DALETOU_LIST
                                                            fromController:self
                                                                withObject:lotteryNumberArray
                                                               withObject2:nil];

}
-(IBAction)clearSelect:(id)sender{
    [lotteryNumber clear];
    countlabel.text = @"0";
    moneylabel.text = @"0";
    for (UIView *subView in self.view.subviews) {
        if ([[subView class] isSubclassOfClass:[UIButton class]] || 
            subView.tag == 23 ||
            subView.tag == 32) {
            [((UIButton*)subView) setSelected:NO];
        }
    }
}
-(IBAction)sureSelect:(id)sender{
    if ([[JddPickNumDaLeTouListViewController sharedInstance].numberListTable numberOfRowsInSection:0]>0) {
        if ([lotteryNumber.headBallArray count]>0||[lotteryNumber.backBallArray count]>0) {
            if ([lotteryNumber.headBallArray count] < 5) {
                [JddCommonFunction messageBoxWithMessage:BALL_COUNT_NOT_CORRECT_HEAD];
                return;
            }else if ([lotteryNumber.backBallArray count] < 2) {
                [JddCommonFunction messageBoxWithMessage:BALL_COUNT_NOT_CORRECT_BACK];
                return;
            }else {
                [lotteryNumberArray removeAllObjects];
                JddDaletouNumber *newNumber = [[JddDaletouNumber alloc] init];
                [newNumber.backBallArray addObjectsFromArray:lotteryNumber.backBallArray];
                [newNumber.headBallArray addObjectsFromArray:lotteryNumber.headBallArray];
                
                [lotteryNumberArray addObject:newNumber];
                [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_PICK_NUM_DALETOU_LIST 
                                                                     fromController:self 
                                                                         withObject:lotteryNumberArray 
                                                                        withObject2:currentLotteryIssue];
            }
            
            
        }else if ([lotteryNumber.headBallArray count]==0&&[lotteryNumber.backBallArray count]==0) {
            [[JddViewControllerManager sharedInstance].navigationController pushViewController:[JddPickNumDaLeTouListViewController sharedInstance] animated:YES];
        }                
    }else {
        
        if ([lotteryNumber.headBallArray count] < 5) {
            [JddCommonFunction messageBoxWithMessage:BALL_COUNT_NOT_CORRECT_HEAD];
            return;
        }else {
            if ([lotteryNumber.backBallArray count] < 2) {
                [JddCommonFunction messageBoxWithMessage:BALL_COUNT_NOT_CORRECT_BACK];
                return;
            }
        }
        
        [lotteryNumberArray removeAllObjects];
        JddDaletouNumber *newNumber = [[JddDaletouNumber alloc] init];
        [newNumber.backBallArray addObjectsFromArray:lotteryNumber.backBallArray];
        [newNumber.headBallArray addObjectsFromArray:lotteryNumber.headBallArray];
        
        [lotteryNumberArray addObject:newNumber];
        [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_PICK_NUM_DALETOU_LIST 
                                                             fromController:self 
                                                                 withObject:lotteryNumberArray 
                                                                withObject2:currentLotteryIssue];
    }

}

-(void)destoryView{
    [lotteryNumber clear];
    countlabel.text = @"0";
    moneylabel.text = @"0";
    [UIAccelerometer sharedAccelerometer].delegate = nil;
    sharked = true;
    for (UIView *subView in self.view.subviews) {
        if ([[subView class] isSubclassOfClass:[UIButton class]] || 
            subView.tag == 23 ||
            subView.tag == 32) {
            [((UIButton*)subView) setSelected:NO];
        }
    }
}

- (IBAction)numberButtonClicked:(id)sender{
    UIButton *button = sender;
    
    if (button.tag == 23) {
            [button setSelected:![button isSelected]];
            if ([button isSelected]) {
                if ([lotteryNumber.headBallArray count]>17) {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"前区最多选择18个。" delegate:self cancelButtonTitle:@"确定"otherButtonTitles:nil,nil ];
                    [alert show];
                    [button setSelected:![button isSelected]];
                }else{
                [lotteryNumber addheadBallNumber:[button.titleLabel.text intValue]];
                    [JddCommonFunction animationViewWithZoomOutIn:button delaySecond:0];
                }
            }
            else {
                [lotteryNumber removeheadBallNumber:[button.titleLabel.text intValue]];
            }
        }
    
    
    if (button.tag == 32) {
        [button setSelected:![button isSelected]];
        if ([button isSelected]) {
            [lotteryNumber addbackBallNumber:[button.titleLabel.text intValue]];
            [JddCommonFunction animationViewWithZoomOutIn:button delaySecond:0];
        }
        else {
            [lotteryNumber removebackBallNumber:[button.titleLabel.text intValue]];
        }
    }
    
    self.countlabel.text=[NSString stringWithFormat:@"%d", [JddCommonFunction countDaLeTouTotalNumber:[lotteryNumber.headBallArray count] backBallAmount:[lotteryNumber.backBallArray count]]];
    self.moneylabel.text = [NSString stringWithFormat:@"%d", [JddCommonFunction countDaLeTouTotalNumber:[lotteryNumber.headBallArray count] backBallAmount:[lotteryNumber.backBallArray count]]*2];
}


-(void)selectHeadBall:(NSNumber*)buttonIndex multiple:(NSNumber*)multiple{
    [lotteryNumber clearheadBallNumber];
    if ([buttonIndex intValue] == 1) {
        [JddCommonFunction generateheadBallOfDaLeTouNumber:lotteryNumber count:[multiple intValue]];
        
        for (UIView *subView in self.view.subviews) {
            if ([[subView class] isSubclassOfClass:[UIButton class]] && subView.tag == 23) {
                BOOL shouldSelected = NO;
                if ([lotteryNumber headBallHasNumber:[((UIButton*)subView).titleLabel.text intValue]]) {
                    shouldSelected = YES;
                }
                [((UIButton*)subView) setSelected:shouldSelected];
                if(shouldSelected == TRUE){
                    [JddCommonFunction animationViewWithZoomOutIn:subView delaySecond:0];
                }
            }
        }
        self.countlabel.text=[NSString stringWithFormat:@"%d", [JddCommonFunction countDaLeTouTotalNumber:[lotteryNumber.headBallArray count] backBallAmount:[lotteryNumber.backBallArray count]]];
        self.moneylabel.text = [NSString stringWithFormat:@"%d", [JddCommonFunction countDaLeTouTotalNumber:[lotteryNumber.headBallArray count] backBallAmount:[lotteryNumber.backBallArray count]]*2];

    }
}

-(void)selectBackBall:(NSNumber*)buttonIndex multiple:(NSNumber*)multiple{
    [lotteryNumber clearbackBallNumber];
    if ([buttonIndex intValue] == 1) {        
        [JddCommonFunction generatebackBallOfDaLeTouNumber:lotteryNumber count:[multiple intValue]];
        for (UIView *subView in self.view.subviews) {
            if ([[subView class] isSubclassOfClass:[UIButton class]] && subView.tag == 32) {
                BOOL shouldSelected = NO;
                if ([lotteryNumber backBallHasNumber:[((UIButton*)subView).titleLabel.text intValue]]) {
                    shouldSelected = YES;
                }
                [((UIButton*)subView) setSelected:shouldSelected];
                if(shouldSelected == TRUE){
                    [JddCommonFunction animationViewWithZoomOutIn:subView delaySecond:0];
                }
            }
        }
        self.countlabel.text=[NSString stringWithFormat:@"%d", [JddCommonFunction countDaLeTouTotalNumber:[lotteryNumber.headBallArray count] backBallAmount:[lotteryNumber.backBallArray count]]];
        self.moneylabel.text = [NSString stringWithFormat:@"%d", [JddCommonFunction countDaLeTouTotalNumber:[lotteryNumber.headBallArray count] backBallAmount:[lotteryNumber.backBallArray count]]*2];        
    }
}

- (IBAction)randomSelectRedBall:(id)sender{  
    
//    CGRect rect = [[UIScreen mainScreen] bounds];
//    rect.origin.x = (rect.size.width - 251) / 2.0;
//    rect.origin.y = (rect.size.height - 139) / 2.0;
//    rect.size.width = 251.0;
//    rect.size.height = 139.0;
//    randomSelectNumberDialog = [JddRandomSelectNumView getInstanceView];
//    [randomSelectNumberDialog setFrame:rect];
//    randomSelectNumberDialog.type =4;
//    randomSelectNumberDialog.multipleTextField.text = @"5";
//    randomSelectNumberDialog.typelabel.text = @"前区至少机选5个号码";
//    randomSelectNumberDialog.delegate = self;
//    [randomSelectNumberDialog show];
    [randomSelectNumberDialog show];
    [self selectHeadBall:[NSNumber numberWithInt:1] multiple:[NSNumber numberWithInt:5]];
    [self selectBackBall:[NSNumber numberWithInt:1] multiple:[NSNumber numberWithInt:2]];
    
}

- (IBAction)randomSelectBlueBall:(id)sender{
    
    CGRect rect = [[UIScreen mainScreen] bounds];
    rect.origin.x = (rect.size.width - 251) / 2.0;
    rect.origin.y = (rect.size.height - 139) / 2.0;
    rect.size.width = 251.0;
    rect.size.height = 139.0;
    randomSelectNumberDialog = [JddRandomSelectNumView getInstanceView];
    [randomSelectNumberDialog setFrame:rect];
    randomSelectNumberDialog.type =5;
    randomSelectNumberDialog.multipleTextField.text = @"2";
    randomSelectNumberDialog.typelabel.text = @"后区至少机选2个号码";
    randomSelectNumberDialog.delegate = self;
    [randomSelectNumberDialog show];

}


- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration{
    
    
    static NSInteger shakeCount = 0;
    static NSDate *shakeStart;
    NSDate *now = [[NSDate alloc] init];
    NSDate *checkDate = [[NSDate alloc] initWithTimeInterval:1.5f sinceDate:shakeStart];
    if ([now compare:checkDate] == NSOrderedDescending || shakeStart == nil)
    {
            shakeCount = 0;
            shakeStart = [[NSDate alloc] init];
    }
    
    if ((fabsf(acceleration.x) > 1.0 || fabsf(acceleration.y) > 1.0 || fabsf(acceleration.z) > 1.1)&&!sharked)
    {
        shakeCount++;
    }
    
    if (shakeCount > 0)
    {
        shakeCount = 0;
        shakeStart = [[NSDate alloc] init];
        
        [lotteryNumber clearheadBallNumber];
        [JddCommonFunction generateheadBallOfDaLeTouNumber:lotteryNumber count:5];
        
        for (UIView *subView in self.view.subviews) {
            if ([[subView class] isSubclassOfClass:[UIButton class]] && subView.tag == 23) {
                BOOL shouldSelected = NO;
                
                if ([lotteryNumber headBallHasNumber:[((UIButton*)subView).titleLabel.text intValue]]) {
                    shouldSelected = YES;
                }
                
                [((UIButton*)subView) setSelected:shouldSelected];
            }
        }
        
        [lotteryNumber clearbackBallNumber];
        [JddCommonFunction generatebackBallOfDaLeTouNumber:lotteryNumber count:2];
        
        for (UIView *subView in self.view.subviews) {
            if ([[subView class] isSubclassOfClass:[UIButton class]] && subView.tag == 32) {
                BOOL shouldSelected = NO;
                
                if ([lotteryNumber backBallHasNumber:[((UIButton*)subView).titleLabel.text intValue]]) {
                    shouldSelected = YES;
                }
                
                [((UIButton*)subView) setSelected:shouldSelected];
            }
        }

        
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
        self.countlabel.text=[NSString stringWithFormat:@"%d", [JddCommonFunction countDaLeTouTotalNumber:[lotteryNumber.headBallArray count] backBallAmount:[lotteryNumber.backBallArray count]]];
        self.moneylabel.text = [NSString stringWithFormat:@"%d", [JddCommonFunction countDaLeTouTotalNumber:[lotteryNumber.headBallArray count] backBallAmount:[lotteryNumber.backBallArray count]]*2];

    }
    

    
}

- (void)countDownTimer:(NSTimer*)thisTimer{
    currentTime = [currentTime dateByAddingTimeInterval:1];
    
    NSTimeInterval interval = [endTime timeIntervalSinceDate:currentTime];
    if (interval < 0) {
        [countDownTimer invalidate];
        JddQueryDigitalLotteryIssueOperation *operation = [[JddQueryDigitalLotteryIssueOperation alloc] init];
        operation.delegate = self;
        operation.lotteryTypeId = [NSString stringWithString:@"39"];
        [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
         
    }else {
        NSInteger remainDay = interval / 86400;
        NSInteger remainHour = (interval - 86400 * remainDay) / 3600;
        NSInteger remainMinute = (interval - 86400 * remainDay - remainHour * 3600) / 60;
        NSInteger remainSecond = (interval - 86400 * remainDay - remainHour *3600 - remainMinute * 60);
        remainTimeLabel.text = [NSString stringWithFormat:@"%d天%d小时%d分%d秒", remainDay, remainHour, remainMinute, remainSecond];
    }
}

- (void)QueryDigitalLotteryIssueOperationResult:(NSData *)result{
    if (result) {
        if ([JddDataParser parseLotteryIssueResult:result lotteryIssue:currentLotteryIssue]){
            issueCodeLabel.text = [NSString stringWithFormat:@"第%@期",currentLotteryIssue.name];
            endTime = [JddCommonFunction dateFromString:currentLotteryIssue.endTime];
            currentTime = [JddCommonFunction dateFromString:currentLotteryIssue.currentTime];
            
            countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 
                                                              target:self 
                                                            selector:@selector(countDownTimer:) 
                                                            userInfo:nil 
                                                             repeats:YES];
        }
    }
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (void)loadNavBar
{
     
    UIButton *right = [UIButton buttonWithType:UIButtonTypeCustom];
    right.frame = CGRectMake(0, 0, 40, 30);
    [right setTitle:@"帮助" forState:UIControlStateNormal];
    right.titleLabel.font = [UIFont systemFontOfSize:15];
    [right setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [right addTarget:self action:@selector(listSelect) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:right];
    
}
//- (void)backView
//{
//    [self.navigationController popViewControllerAnimated:YES];
//}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self loadNavBar];
    sharked = TRUE;
    for (UIView *subView in self.view.subviews) {
        if ([[subView class] isSubclassOfClass:[UIButton class]]) {
            NSInteger number = [((UIButton*)subView).titleLabel.text intValue];
            int tagnumber = ((UIButton*)subView).tag;
            if (number > 0 && number < 36&&tagnumber == 23) {
                [((UIButton*)subView) setBackgroundImage:[UIImage imageNamed:@"jdd_redbollselected"] forState:UIControlStateSelected];
                [((UIButton*)subView) setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
            }            if (number > 0 && number < 36&&tagnumber == 32) {
                [((UIButton*)subView) setBackgroundImage:[UIImage imageNamed:@"jdd_bulebollselected.png"] forState:UIControlStateSelected];
                [((UIButton*)subView) setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
            }
        }
    }
    

    
//    [self.navigationItem setTitle:PAGE_DALETOU_PICK_NUMBER];
    
        UILabel *customLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
        customLab.backgroundColor = [UIColor clearColor];
        [customLab setText:PAGE_DALETOU_PICK_NUMBER];
        customLab.textAlignment = NSTextAlignmentCenter;

        [customLab setTextColor:[UIColor whiteColor]];
        customLab.font = [UIFont systemFontOfSize:19];
        self.navigationItem.titleView = customLab;
    
    currentLotteryIssue = [[JddLotteryIssue alloc] init];
    lotteryNumber = [[JddDaletouNumber alloc] init];
    lotteryNumberArray = [NSMutableArray array];
}

-(void)listSelect{
//    CGRect rect = [[UIScreen mainScreen] bounds];
//    rect.origin.x = (rect.size.width) / 2.0;
//    rect.origin.y = (rect.size.height) / 2.0;
//    rect.size.width = 251.0;
//    rect.size.height = 300.0;
//    indexList = [JddIndexListView getInstanceView];
//    [indexList setFrame:rect];
//    indexList.type = 0;
//    indexList.delegate = self;
//    [indexList show];
    
    NoticeViewController *noticeView = [[NoticeViewController alloc] init];
    noticeView.webInfoId = LOTTERY_TYPE_ID_DALETOU;
    [self.navigationController pushViewController:noticeView animated:YES];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if ([alertView.message isEqualToString:@"您还没有登录，请先登录"]) {
        if (buttonIndex == 0) {
            [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:
             CONTROLLER_LOGIN 
                                                                 fromController:self
                                                                     withObject:nil 
                                                                    withObject2:nil];
        }else{
            
        }
    }
}

//-(void)selectorbutton1{
//    [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_LOTTERY_OPEN_LIST
//                                                         fromController:self 
//                                                             withObject:@"39" 
//                                                            withObject2:nil];
//}
//
//-(void)selectorbutton2{
//    if (![JddCommonFunction isLogin]) {
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"玩球球"
//                                                        message:@"您还没有登录，请先登录"
//                                                       delegate:self
//                                              cancelButtonTitle:@"确定"
//                                              otherButtonTitles:@"取消", nil]
//        ; 
//        [alert show];
//    }else {
//        [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_BUY_HISTORY 
//                                                             fromController:self 
//                                                                 withObject:[NSNumber numberWithInt:LOTTERY_TYPE_ID_DALETOU]
//                                                                withObject2:nil];
//    }
//}
//
//-(void)selectorbutton3{
//    [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_HOW_TO_PLAY_SSQ
//                                                         fromController:self 
//                                                             withObject:nil 
//                                                            withObject2:nil];
//}
//
//-(void)selectorbutton4{
//    if (![JddCommonFunction isLogin]) {
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"玩球球"
//                                                        message:@"您还没有登录，请先登录"
//                                                       delegate:self
//                                              cancelButtonTitle:@"确定"
//                                              otherButtonTitles:@"取消", nil]
//        ; 
//        [alert show];
//    }else {
//        [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_FOLLOW_NUMBER_HISTORY 
//                                                             fromController:self 
//                                                                 withObject:nil 
//                                                                withObject2:nil];
//    }
//}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"DLT"];
    [MobClick event:@"Lottery-DLT"];

    [[UIAccelerometer sharedAccelerometer] setDelegate:self];
    [[UIAccelerometer sharedAccelerometer] setUpdateInterval:1.0];
    sharked =false;
    [countDownTimer invalidate]; 
    
    JddQueryDigitalLotteryIssueOperation *operation = [[JddQueryDigitalLotteryIssueOperation alloc] init];
    operation.delegate = self;
    operation.lotteryTypeId = @"39";
    [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
    [self randomSelectRedBall:nil];
}

- (void)viewWillDisappear:(BOOL)animated{
    [MobClick endLogPageView:@"DLT"];

    [countDownTimer invalidate];
    [UIAccelerometer sharedAccelerometer].delegate = nil;		
    sharked = true;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
